#!/usr/bin/env python

import argparse
import json
import logging
import os
import re
import time

_DEFAULT_INPUT = '/tmp/1'
_DEFAULT_OUTPUT = '/tmp/qcom_change_sched_commit_messages'
COMMIT_OUTPUT = '/tmp/qcom_change_sched_commit_id'
# KEY_STRING="kernel/sched/"
KEY_STRING="kernel/sched/fair.c"
LINE_BLOCK_LEN=200

#  git log linux-5.4.61..mi-11-888-code-base  --stat  > /tmp/1
#  git log linux-5.4.61..mi-11-888-code-base  --stat | grep "kernel/sched" -B 30 > /tmp/1
def main():
        infile = open(_DEFAULT_INPUT, "r")
        outfile = open(_DEFAULT_OUTPUT, "w")
        commit_id = open(COMMIT_OUTPUT, "w")
        inlist = []
        sched_list = []
        line_block = [[-1, -1]]
        high_line_num = 0
        low_line_num = 0
        j = 0
        k = 0

        for line in infile:
                inlist.append(line)

        for i, line_content in enumerate(inlist):
                if KEY_STRING in line_content:
                        sched_list.append(i)
                        # print ("line: ", i, "sting: ", line_content)
        for i, line_num_str in enumerate(sched_list):
                line_num = int(line_num_str)
                # print ("line_num xx: ", line_num, "content:", inlist[line_num])
                for j in range(0, LINE_BLOCK_LEN):
                        high_line_num = line_num - j
                        if high_line_num >= 0 and re.search("^commit ", inlist[high_line_num]):
                                break
                        if high_line_num < 0:
                                high_line_num = 0
                                break

                if j >= LINE_BLOCK_LEN - 2:
                        print (inlist[line_num - j], "is too long...")
                        continue

                for k in range(0, LINE_BLOCK_LEN):
                        low_line_num = line_num + k
                        if low_line_num < len(inlist) and re.search("^commit ", inlist[low_line_num]):
                                break
                        if low_line_num == len(inlist):
                                low_line_num = len(inlist) - 1
                                break


                if low_line_num - high_line_num < 5 :
                        continue
                if [high_line_num, low_line_num] not in line_block:
                        line_block.append([high_line_num, low_line_num])

        # write result to file
        i = 0
        for arr in line_block:
                # print (arr[0], arr[1])
                if i != 0:
                        for n in range(arr[0], arr[1]):
                                outfile.write(inlist[n])
                        commit_id.write(inlist[arr[0]])
                i = i + 1

        infile.close()
        outfile.close()
        commit_id.close()

if __name__ == '__main__':
    main()
